package test05;

import java.util.ArrayList;
import java.util.List;

// 抽象组件
interface FileSystem {
    void display();
}

// 叶子节点 - 文件
class File implements FileSystem {
    private String name;
    private String type;

    public File(String name, String type) {
        this.name = name;
        this.type = type;
    }

    @Override
    public void display() {
        switch (type.toLowerCase()) {
            case "txt":
                System.out.println("以文本方式显示文件: " + name);
                break;
            case "jpg":
            case "png":
                System.out.println("以图片方式显示文件: " + name);
                break;
            default:
                System.out.println("以默认方式显示文件: " + name);
        }
    }
}

// 复合节点 - 文件夹
class Folder implements FileSystem {
    private String name;
    private List<FileSystem> children;

    public Folder(String name) {
        this.name = name;
        this.children = new ArrayList<>();
    }

    @Override
    public void display() {
        System.out.println("浏览文件夹: " + name);
        for (FileSystem child : children) {
            child.display();
        }
    }

    public void add(FileSystem component) {
        children.add(component);
    }

    public void remove(FileSystem component) {
        children.remove(component);
    }
}

// 客户端代码
public class CompositePatternDemo {
    public static void main(String[] args) {
        // 创建文件
        File file1 = new File("document.txt", "txt");
        File file2 = new File("image.jpg", "jpg");
        File file3 = new File("data.pdf", "pdf");

        // 创建文件夹
        Folder root = new Folder("根目录");
        Folder subFolder = new Folder("子文件夹");

        // 构建树形结构
        root.add(file1);
        root.add(subFolder);
        subFolder.add(file2);
        subFolder.add(file3);

        // 客户端统一操作
        System.out.println("=== 浏览根目录 ===");
        root.display();

        System.out.println("\n=== 浏览子文件夹 ===");
        subFolder.display();

        System.out.println("\n=== 单独浏览文件 ===");
        file1.display();
        file2.display();
    }
}